<template>
  <div>
    <!-- 新增规则 基本字段 -->
    <Modal
      width="600"
      class="add-newrule-modal"
      v-model="baseModalShow"
      :title="isCreateRule ? '新建规则' : '编辑规则'"
      :closable="false"
      :mask-closable="false"
      :transfer="false"
      >
      <Tabs :class="['add-newrule-tab', isCreateRule ? '' : 'edit-rule-tab']">
        <TabPane class="new-rule-tab" label="新建规则" name="addRulesTab">
          <Form
            class="create-rule-form"
            ref="ruleForm"
            :model="newRuleForm"
            :rules="newRuleFormRules"
            label-position="left"
            :label-width="100"
            >
            <FormItem label="规则名称" prop="resName">
              <Input v-model="newRuleForm.resName" placeholder="请输入规则名称"></Input>
            </FormItem>
            <FormItem label="规则编码" prop="resCode">
              <Input v-model="newRuleForm.resCode" placeholder="请输入规则编码"></Input>
            </FormItem>
            <!-- <FormItem label="规则类型" prop="ruleClass">
              <Select v-model="newRuleForm.ruleClass">
                <Option value="ruleClass1">规则类型1</Option>
              </Select>
            </FormItem> -->
            <FormItem label="编辑类型" prop="ruleSetType">
              <Select v-model="newRuleForm.ruleSetType" :disabled="!isCreateRule">
                <Option value="GDRL">视图模式</Option>
                <Option value="DRL">源码模式</Option>
              </Select>
            </FormItem>
            <FormItem label="备注" prop="resDesc">
              <Input v-model="newRuleForm.resDesc" placeholder="请输入备注"></Input>
            </FormItem>
          </Form>
        </TabPane>
        <!-- 导入规则 -->
        <TabPane class="import-rule-tab" label="导入规则" name="importRuleTab">
          <Upload
            multiple
            type="drag"
            action="//jsonplaceholder.typicode.com/posts/">
            <div style="padding: 120px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>将文件拖拽至此处或点击上传</p>
            </div>
          </Upload>
          <p style="text-align: center">仅支持上传.excel文件，且文件不超过10MB，<a>样例下载</a></p>
        </TabPane>
      </Tabs>
      <div slot="footer">
        <Button @click="cancelNewRuleModal">取消</Button>
        <Button @click="saveBaseForm" type="primary">保存</Button>
        <Button type="primary" v-if="currentTabs === 'addRulesTab'" @click="toEditRules" :disabled="isCreateRule && !createRuleSucc">编辑规则</Button>
        <Button type="primary" v-else @click="certainNewRuleModal">确定</Button>
      </div>
    </Modal>
    <!-- 编辑规则 规则详情 -->
    <Modal
      width="1200"
      class="edit-rule-modal"
      v-model="editRuleShow"
      title="编辑规则"
      :mask-closable="false"
      :transfer="false"
      :closable="false"
      >
      <div class="edit-rule-content">
        <ul class="left-content">
          <li class="left-content-data">
            <div class="filter-wrap">
              <p class="filter-board" style="flex: 1; margin-right: 6px;">
                <b>数据类型</b>
                <Select v-model="dataSourece">
                  <Option value="dataStructure">数据结构</Option>
                  <Option value="constData">常量</Option>
                  <Option value="enumerationData">枚举</Option>
                </Select>
              </p>
              <p v-if="dataSourece === 'dataStructure'" class="filter-board" style="flex: 1;">
                <b>数据分类</b>
                <Cascader
                  :data="dataTypeDict"
                  v-model="currentDataType"
                  change-on-select
                  @on-change="changeDataType"></Cascader>
              </p>
              <p v-if="dataSourece === 'enumerationData'" class="filter-board" style="flex: 1;">
                <b>枚举值</b>
                <Cascader
                  :data="enumerationDataListMap"
                  v-model="currentEnumeration"
                  change-on-select
                  @on-change="changeEnumeration"></Cascader>
              </p>
            </div>
            <!-- 输入、输出数据 -->
            <div v-if="dataSourece === 'dataStructure'">
              <div class="class-box scrollbar-small input-data-box">
                <b class="data-title">输入数据：</b>
                <div>
                  <p class="data-title" v-if="ruleInputData.length < 1">未查询到数据</p>
                  <Button
                    class="data-item DS_ellipsis"
                    v-for="item in ruleInputData"
                    :key="item.dataCode"
                    :title="item.dataName"
                    @click="handleClickDataItem(item, 'inputData')">{{ item.dataName }}</Button>
                </div>
              </div>
              <div class="class-box scrollbar-small output-data-box">
                <b class="data-title">输出数据：</b>
                <div>
                  <p class="data-title" v-if="ruleOutputData.length < 1">未查询到数据</p>
                  <Button
                    class="data-item DS_ellipsis"
                    v-for="item in ruleOutputData"
                    :key="item.dataCode"
                    :title="item.dataName"
                    @click="handleClickDataItem(item, 'outputData')">{{ item.dataName }}</Button>
                </div>
              </div>
            </div>
            <!-- 常量数据 -->
            <div v-if="dataSourece === 'constData'" class="class-box scrollbar-small const-data-box">
              <Button
                class="data-item DS_ellipsis"
                v-for="item in constDataList"
                :key="item.constId"
                :title="item.constName"
                @click="handleClickDataItem(item, 'constData')">{{ item.constName }}</Button>
            </div>
            <!-- 枚举数据 -->
            <div v-if="dataSourece === 'enumerationData'" class="class-box scrollbar-small const-data-box">
              <Button
                class="data-item DS_ellipsis"
                v-for="item in enumerationDataList"
                :key="item.dictId"
                :title="item.dictName"
                @click="handleClickDataItem(item, 'enumData')">{{ item.dictName }}</Button>
            </div>
          </li>
          <li class="left-content-methods">
            <p class="filter-board">
              <b>方法分类</b>
              <Select v-model="currentMethodType" @on-change="changeMethodType">
                <!-- <Option value="computation">计算符</Option>
                <Option value="comparison">比较符</Option>
                <Option value="custom">自定义方法</Option> -->
                <Option v-for="item in methodTypeList" :key="item.resId" :value="item.resId">{{ item.resName }}</Option>
              </Select>
            </p>
            <div class="class-box method-class-box scrollbar-small">
              <Button
                class="data-item DS_ellipsis"
                v-for="item in methodList"
                :key="item.methodCode"
                :title="item.methodName"
                @click="handleClickMethodItem(item, currentMethodType)">{{ item.methodName }}</Button>

                <Button
                  class="data-item DS_ellipsis"
                  v-for="item in symbolContent"
                  :key="item.methodCode"
                  :title="item.methodName"
                  @click="handleClickMethodItem(item, currentMethodType)">{{ item.methodName }}</Button>
            </div>
          </li>
          <li class="left-content-value">
            <p class="filter-board">
              <b>运算值</b>
              <Input v-model="operationalValue" @on-enter="handleEnter" placeholder="输入按enter添加"></Input>
            </p>
          </li>
        </ul>
        <div class="right-content">
          <!-- 视图模式 -->
          <div v-if="newRuleForm.ruleSetType === 'GDRL'" class="view-model">
            <ul class="view-box-title clearfix">
              <li>输入规则</li>
              <li>输出结果</li>
              <Button class="add-btn" size="small" shape="circle" icon="md-add" @click="addRuleItem"></Button>
            </ul>
            <ul class="view-box">
              <li class="view-box-item clearfix" v-for="(item, index) in viewRuleList" :key="index">
                <p
                  :class="['left-area', activeArea[0] === index && activeArea[1] === 'conditions' ? 'active-area' : '']"
                  @click="handleClickArea(index, 'conditions')"
                >
                  <Tag
                    v-for="(tag, i) in item.conditions"
                    :key="i"
                    closable
                    @on-close="() => handleCloseTag(index, i, 'conditions')"
                    :class="['view-tag', activeTag[0] == index && activeTag[1] == i && activeTag[2] == 'conditions' ? 'active-tag' : '']"
                    @click.native="handleClickTag(index, i, 'conditions')"
                  >{{ tag.description }}</Tag>
                </p>
                <p
                  :class="['right-area', activeArea[0] === index && activeArea[1] === 'consequence' ? 'active-area' : '']"
                  @click="handleClickArea(index, 'consequence')">
                  <Tag
                    v-for="(tag, i) in item.consequence"
                    :key="i"
                    closable
                    @on-close="() => handleCloseTag(index, i, 'consequence')"
                    :class="['view-tag', activeTag[0] == index && activeTag[1] == i && activeTag[2] == 'consequence' ? 'active-tag' : '']"
                    @click.native="handleClickTag(index, i, 'consequence')"
                  >{{ tag.description }}</Tag>
                </p>
                <Button class="rm-btn" size="small" shape="circle" icon="md-remove" @click="removeRuleItem(index)"></Button>
              </li>
            </ul>
          </div>
          <!-- 源码模式 -->
          <div v-else class="code-model">
            <editor v-model="ruleScript" @init="editorInit" lang="drools" theme="chrome" ref="editor" enableBasicAutocompletion="true" enableSnippets="true" enableLiveAutocompletion="true" class="ruleShowSpace"></editor>
          </div>
        </div>
      </div>

      <div class="edit-rule-footer clearfix" slot="footer">
        <!-- <p class="left-btn">
          <RadioGroup v-model="currentRuleViewModel" type="button" size="large">
            <Radio label="viewModel" :disabled="currentRuleViewModel === 'codeModel' && ruleScript.length > 0">视图模式</Radio>
            <Radio label="codeModel">源码模式</Radio>
          </RadioGroup>
        </p> -->
        <p class="right-btn">
          <Button @click="clearRule">
            清空
          </Button>
          <Button @click="cancelEditRuleModal">取消</Button>
          <Button type="primary" @click="certainEditRuleModal">确定</Button>
        </p>
      </div>
    </Modal>
  </div>
</template>

<script>
import { showMessageTip, addProp, flatten } from '@/libs/util'
import { ruleComputation, ruleComparison, ruleSymbol } from '@/view/project-preview/commonMethodContent'
import { addResourceBaseInfoApi, updateResourceBaseInfoByIdApi, queryResourceContentByIdApi, updateResourceContentByIdApi } from '@/api/project-resource'
import { queryDictByKeyApi } from '@/api/business-type'
import { queryConstApi } from '@/api/data-management'
import { queryMethodJarApi, queryMethodApi } from '@/api/method-management'
export default {
  name: 'edit-rule',
  props: ['newRuleModalShow', 'projectId'],
  data () {
    const validateDataCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('数据编码不能为空'))
      } else if (!/^[a-z|A-Z][a-z|A-Z|_|0-9]*$/.test(value)) {
        callback(new Error('数据编码只能以字母开头，包含字母、数字、下划线'))
      } else {
        callback()
      }
    }

    return {
      currentTabs: 'addRulesTab',
      // 新增规则基本信息标识
      isCreateRule: true,
      // 新增规则基本信息成功标识
      createRuleSucc: false,
      // 新建规则表单
      newRuleForm: {
        resName: '',
        resCode: '',
        // ruleClass: '',
        ruleSetType: '',
        resDesc: '',
        resType: 'rule'
      },
      newRuleFormRules: {
        resName: [{
          required: true,
          message: '规则名称不能为空',
          trigger: 'blur'
        }],
        resCode: [{
          required: true,
          trigger: 'blur',
          validator: validateDataCode
        }],
        // ruleClass: [{
        //   required: true,
        //   message: '规则类型不能为空',
        //   trigger: 'change'
        // }],
        ruleSetType: [{
          required: true,
          message: '编辑类型不能为空',
          trigger: 'change'
        }]
      },

      // 编辑规则modal框相关
      dataSourece: 'dataStructure',
      // 数据分类字典
      dataTypeDict: [],
      // 数据分类级联框绑定数据
      currentDataType: [],
      ruleInputData: [],
      ruleOutputData: [],
      // 存储全量输入数据
      ruleInputDataMap: [],
      // 存储全量输出数据
      ruleOutputDataMap: [],
      // 常量列表
      constDataList: [],
      editRuleShow: false,
      // 枚举数据列表
      enumerationDataList: [],
      enumerationDataListMap: [],
      // 枚举值级联框绑定数据
      currentEnumeration: [],
      flattenTreeList: [],
      // 方法分类绑定值
      currentMethodType: 'computation',
      // 运算值绑定值
      operationalValue: '',
      ruleScript:
        'package rules\r\nimport java.util.Map;\r\nimport net.tdfintech.decision.engine.util.executor.DataUtil;\r\nimport net.tdfintech.decision.engine.util.executor.MethodUtil;\r\nrule "rule1" //此处引号内填写自定义名称\r\nwhen\r\n\t$map : Map(); //此处括号内填写条件表达式，如‘DataUtil.get(this,"$age")>=18&&DataUtil.get(this,"$age")<=60’\r\nthen\t\r\n\t$map.put("",""); //此处括号内填写规则输出结果，第一个值为输出数据编码，第二个值为自定义字符\r\nend',
      ruleScriptTmp:
        'package rules\r\nimport java.util.Map;\r\nimport net.tdfintech.decision.engine.util.executor.DataUtil;\r\nimport net.tdfintech.decision.engine.util.executor.MethodUtil;\r\nrule "rule1" //此处引号内填写自定义名称\r\nwhen\r\n\t$map : Map(); //此处括号内填写条件表达式，如‘DataUtil.get(this,"$age")>=18&&DataUtil.get(this,"$age")<=60’\r\nthen\t\r\n\t$map.put("",""); //此处括号内填写规则输出结果，第一个值为输出数据编码，第二个值为自定义字符\r\nend',
      classifyOptions: [],
      editorCtrl: '',
      // 方法分类 comparison
      methodTypeList: [],
      // 左侧展示区方法按钮
      methodList: [],
      // 自定义方法列表
      customMethodList: [],
      // 计算符
      computationContent: ruleComputation,
      // 比较符
      comparisonContent: ruleComparison,
      // 符号
      symbolContent: ruleSymbol,
      // 视图模式 规则list
      viewRuleList: [
        {
          conditions: [],
          consequence: []
        }
      ],
      // ['index', 'conditon'] index为viewRuleList的索引 conditon标识输入规则 consequence标识输出结果
      activeArea: ['', ''],
      // 当前选中tag
      activeTag: ['', '', ''],
      // 记录content versionId
      resVerId: null
    }
  },
  components: {
    editor: require('vue2-ace-editor')
  },
  computed: {
    baseModalShow () {
      return this.newRuleModalShow
    },
    proId () {
      return this.projectId
    }
  },
  methods: {
    // 源码模式下 editor初始化
    editorInit (initCtrl) {
      require('brace/ext/language_tools') // language extension prerequsite...
      require('brace/mode/drools') // language
      require('brace/theme/chrome')
      require('brace/snippets/drools') // snippet
      initCtrl.setOptions({
        enableBasicAutocompletion: true,
        enableLiveAutocompletion: true
      })
      initCtrl.setFontSize(14)
      this.editorCtrl = initCtrl
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
    },
    // 新增
    addNewRuleForm () {
      this.resetForm()
      this.createRuleSucc = false
      this.isCreateRule = true
    },
    /**
     * 编辑回写基本信息表单
     * @param {formData} [Object] 表单信息
      */
    setEditForm (formData) {
      this.resetForm()
      this.isCreateRule = false
      this.newRuleForm = JSON.parse(JSON.stringify(formData))
      this.newRuleForm.resType = 'rule'
      delete this.newRuleForm._index
      delete this.newRuleForm._rowKey
    },
    // 新增规则modal框取消按钮
    cancelNewRuleModal () {
      this.$emit('on-add-cancel')
    },
    // 新增规则modal框确定按钮
    certainNewRuleModal () {

    },
    // 编辑规则
    toEditRules () {
      this.getDictData()
      this.getConstList()
      this.getMethodList()
      this.editRuleShow = true
      const pathname = location.pathname
      const { inputDataList = [] } = this.$store.state.app.dataStructure[pathname]
      const { outputDataList = [] } = this.$store.state.app.dataStructure[pathname]
      // 赋值输入、输出数据信息
      this.ruleInputDataMap = JSON.parse(JSON.stringify(inputDataList))
      this.ruleOutputDataMap = JSON.parse(JSON.stringify(outputDataList))
      this.ruleInputData = JSON.parse(JSON.stringify(inputDataList))
      this.ruleOutputData = JSON.parse(JSON.stringify(outputDataList))
      // 赋值方法信息
      this.methodList = this.computationContent
      this.getResourceContent()
      if (this.newRuleForm.ruleSetType === 'DRL') {
        this.editorCtrl.focus()
        this.editorCtrl.moveCursorTo(6, 12)
      }
    },
    // 获取规则最新信息
    getResourceContent () {
      this.resVerId = null
      const params = {
        projectId: this.proId,
        resId: this.newRuleForm.resId
      }
      queryResourceContentByIdApi(params).then((res) => {
        if (res.data.code === 2000) {
          if (res.data.data && res.data.data.content) {
            this.resVerId = res.data.data.resVerId || null
            // todo 赋值操作
            const result = res.data.data.content || []
            // 视图模式
            if (typeof (result) === 'object') {
              result.forEach(item => {
                const consequence = []
                item.consequence.forEach((ele, index) => {
                  consequence.push(...ele)
                  if (item.consequence.length > 1 && index < item.consequence.length - 1) {
                    consequence.push({
                      token: '&&',
                      description: 'AND'
                    })
                  }
                })
                item.consequence = consequence
              })
              this.viewRuleList = result
            } else {
              this.ruleScript = result
            }
          }
        }
      })
    },
    // 保存基本信息
    saveBaseForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return
        // 新增规则基本信息接口
        if (this.isCreateRule) {
          const params = {
            projectId: this.proId
          }
          const data = this.newRuleForm
          addResourceBaseInfoApi(params, data).then((res) => {
            const code = res.data.code
            const successText = '新建基本信息成功'
            const errorText = res.data.msg || '新建基本信息失败，请重试'
            showMessageTip(this, code, successText, errorText)
            if (code === 2000) {
              this.isCreateRule = false
              this.createRuleSucc = true
              this.$emit('update-table')
            }
          })
        } else {
          // 更新规则基本信息
          const params = {
            projectId: this.proId,
            resId: this.newRuleForm.resId
          }
          const data = this.newRuleForm
          updateResourceBaseInfoByIdApi(params, data).then((res) => {
            const code = res.data.code
            const successText = '更新基本信息成功'
            const errorText = res.data.msg || '更新基本信息失败，请重试'
            showMessageTip(this, code, successText, errorText)
            if (code === 2000) {
              this.$emit('update-table')
            }
          })
        }
      })
    },
    /* 编辑规则相关 */
    getDictData () {
    // 获取数据分类级联框数据
      const params = {
        dictKey: 'dataType'
      }
      queryDictByKeyApi(params).then((res) => {
        if (res.data.code === 2000) {
          const data = res.data.data
          const propArray = [{
            targetKey: 'dictId',
            hopeKey: 'value'
          }, {
            targetKey: 'dictName',
            hopeKey: 'label'
          }]
          this.dataTypeDict = data.children && data.children.length > 0 ? addProp(data.children, [], propArray) : []
        }
      })
      // 获取枚举数据列表
      queryDictByKeyApi({dictKey: 'dataDict'}).then((res) => {
        if (res.data.code === 2000) {
          const data = res.data.data
          const propArray = [{
            targetKey: 'dictId',
            hopeKey: 'value'
          }, {
            targetKey: 'dictName',
            hopeKey: 'label'
          }]
          this.enumerationDataList = data.children && data.children.length > 0 ? addProp(data.children, [], propArray) : []
          this.enumerationDataListMap = JSON.parse(JSON.stringify(this.enumerationDataList))

          this.flattenTreeList = flatten(this.enumerationDataListMap, ['dictKey', 'dictName', 'dictId', 'parentId', 'children'])
        }
      })
    },
    // 获取常量列表
    getConstList () {
      queryConstApi().then((res) => {
        if (res.data.code === 2000) {
          this.constDataList = res.data.data ? res.data.data : []
        } else {
          this.$Message.error({
            content: res.data.msg || '常量加载失败，请重试',
            duration: 4
          })
        }
      })
    },
    // 获取自定义方法集拼接“方法分类”下拉
    getMethodList () {
      this.methodTypeList = [{
        resId: 'computation',
        resName: '计算符'
      }, {
        resId: 'comparison',
        resName: '比较符'
      }]
      queryMethodJarApi().then((res) => {
        const data = res.data.data && res.data.data.length ? res.data.data : []
        this.methodTypeList = this.methodTypeList.concat(data)
      })
    },
    // 改变数据分类级联框事件
    changeDataType (value) {
      if (value.length) {
        const dataTypeId = value[value.length - 1]
        this.ruleInputData = this.ruleInputDataMap.filter(item => item.dataTypeId === dataTypeId)
        this.ruleOutputData = this.ruleOutputDataMap.filter(item => item.dataTypeId === dataTypeId)
      } else {
        this.ruleInputData = JSON.parse(JSON.stringify(this.ruleInputDataMap))
        this.ruleOutputData = JSON.parse(JSON.stringify(this.ruleOutputDataMap))
      }
    },
    // 改变枚举值级联框事件
    changeEnumeration (value) {
      if (value.length) {
        this.enumerationDataList = this.flattenTreeList.filter(item => item.dictId === value[value.length - 1])[0].children || []
      }
    },
    // 改变方法分类下拉框事件
    changeMethodType (value) {
      switch (value) {
        case 'computation':
          this.methodList = this.computationContent
          break
        case 'comparison':
          this.methodList = this.comparisonContent
          break
        default:
          const params = {
            jarId: value
          }
          queryMethodApi(params).then((res) => {
            if (res.data.code === 2000) {
              this.methodList = res.data.data && res.data.data.methods ? res.data.data.methods : []
            }
          })
          break
      }
    },
    /**
     * 得到对应视图“数据”的code代码片段
     * @param {item} [Object] 数据分类 某个数据详情
      */
    getDataCode (item) {
      const result = `DataUtil.get(this,"${item.dataCode}")`
      return result
    },
    /**
     * 得到对应视图“方法”的token及description代码片段
     * @param {item} [Object] 数据分类 某个数据详情
      */
    getMethodCode (item) {
      let result = [{
        token: `MethodUtil.call("${item.methodCode}"`,
        description: `调用 ( ${item.methodName}`
      }]
      if (item.parameters && item.parameters.length > 0) {
        item.parameters.forEach(ele => {
          result.push({
            token: ',',
            description: ','
          })
        })
      }
      result.push({
        token: ')',
        description: ')'
      })
      return result
    },
    /**
     * 得到“方法”对应视图
     * @param {item} [Object] 数据分类 某个数据详情
      */
    // getMethodName (item) {
    //   let result = [`调用 ( ${item.methodName}`]
    //   if (item.parameters && item.parameters.length > 0) {
    //     item.parameters.forEach(ele => {
    //       result.push(',')
    //     })
    //   }
    //   result.push(')')
    //   return result
    // },
    // 点击数据事件
    handleClickDataItem (item, source) {
      if (this.newRuleForm.ruleSetType === 'GDRL') {
        if (this.activeArea[1].length < 1) {
          this.$Message.warning({
            content: '请选择要添加的目标位置',
            duration: 4
          })
          return
        }
        if (source === 'inputData' && this.activeArea[1] === 'consequence') {
          this.$Message.warning({
            content: '输入数据不能添加至输出结果',
            duration: 4
          })
          return
        } else if (source === 'outputData' && this.activeArea[1] === 'conditions') {
          this.$Message.warning({
            content: '输出数据不能添加至输入规则',
            duration: 4
          })
          return
        }
      }
      let token = ''
      let description = ''
      // 输入数据 or 输出数据
      if (source === 'inputData') {
        token = this.getDataCode(item)
        description = item.dataName
      } else if (source === 'outputData') {
        token = item.dataCode
        description = item.dataName
      } else if (source === 'constData') {
        // 常量
        token = item.constValue
        description = item.constName
      } else if (source === 'enumData') {
        // 枚举
        token = item.dictKey
        description = item.dictName
      }
      // 若为源码模式
      if (this.newRuleForm.ruleSetType === 'DRL') {
        this.editorCtrl.insert(token)
        this.editorCtrl.focus()
        return
      }
      // 若选中了某个tag 则插入选中位置前一个
      if (this.activeTag[2].length > 0) {
        // this.viewRuleList.splice()
        const targetItem = this.viewRuleList[this.activeTag[0]][this.activeTag[2]]
        targetItem.splice(this.activeTag[1], 0, {token, description})
        this.activeTag[1] += 1
      } else {
        // 若没选中tag 则push
        const targetItem = this.viewRuleList[this.activeArea[0]][this.activeArea[1]]
        targetItem.push({token, description})
      }
    },
    // 点击方法事件
    handleClickMethodItem (item, source) {
      if (this.newRuleForm.ruleSetType === 'GDRL') {
        if (this.activeArea[1].length < 1) {
          this.$Message.warning({
            content: '请选择要添加的目标位置',
            duration: 4
          })
          return
        }
        //
        if (source === 'comparison' && this.activeArea[1] === 'consequence') {
          this.$Message.warning({
            content: '比较字符不能添加至输出结果',
            duration: 4
          })
          return
        }
      }

      let token = ''
      let description = ''
      let methodCodeList = []
      // 计算符or比较字符
      if (!item.methodId) {
        token = item.methodCode
        description = item.methodName
        // 若为源码模式
        if (this.newRuleForm.ruleSetType === 'DRL') {
          this.editorCtrl.insert(token)
          this.editorCtrl.focus()
          return
        }
        // 视图模式 选中tag
        if (this.activeTag[2].length > 0) {
          const targetItem = this.viewRuleList[this.activeTag[0]][this.activeTag[2]]
          targetItem.splice(this.activeTag[1], 0, {token, description})
          this.activeTag[1] += 1
        } else {
          // 若没选中tag 则push
          const targetItem = this.viewRuleList[this.activeArea[0]][this.activeArea[1]]
          targetItem.push({token, description})
        }
      } else {
        // 方法
        methodCodeList = this.getMethodCode(item)
        if (this.newRuleForm.ruleSetType === 'DRL') {
          const code = methodCodeList.map(item => item.token).join('')
          this.editorCtrl.insert(code)
          return
        }
        // 若选中tag
        if (this.activeTag[2].length > 0) {
          const targetItem = this.viewRuleList[this.activeTag[0]][this.activeTag[2]]
          targetItem.splice(this.activeTag[1], 0, ...methodCodeList)
        } else {
          // 若没选中tag
          this.viewRuleList[this.activeArea[0]][this.activeArea[1]] = this.viewRuleList[this.activeArea[0]][this.activeArea[1]].concat(methodCodeList)
        }
      }
    },
    // 运算值enter事件
    handleEnter () {
      if (!this.operationalValue) return false
      const reg = new RegExp(/^[a-zA-Z0-9\u4e00-\u9fa5]+$/)
      if (!reg.test(this.operationalValue)) {
        this.$Message.warning({
          content: '请输入数字、字母、汉字',
          duration: 4
        })
        return false
      }
      const token = this.operationalValue
      const description = this.operationalValue
      // 若为源码模式
      if (this.newRuleForm.ruleSetType === 'DRL') {
        this.editorCtrl.insert(token)
        this.editorCtrl.focus()
        return
      }
      // 若选中了tag
      if (this.activeTag[2].length > 0) {
        const targetItem = this.viewRuleList[this.activeTag[0]][this.activeTag[2]]
        targetItem.splice(this.activeTag[1], 0, {token, description})
        this.activeTag[1] += 1
      } else {
        // 若没选中tag 则push
        const targetItem = this.viewRuleList[this.activeArea[0]][this.activeArea[1]]
        targetItem.push({token, description})
      }
    },
    // 加号按钮
    addRuleItem () {
      const tmp = {
        conditions: [],
        consequence: []
      }
      this.viewRuleList.push(tmp)
    },
    // 减号事件
    removeRuleItem (index) {
      if (this.viewRuleList.length === 1) {
        this.$Message.warning({
          content: '至少填写一条规则',
          duration: 4
        })
        return
      }
      this.viewRuleList.splice(index, 1)
    },
    // 点击输入规则、输出结果 空白区域
    handleClickArea (index, target) {
      this.activeArea = [index, target]
    },
    // 关闭标签
    handleCloseTag (index, i, target) {
      this.viewRuleList[index][target].splice(i, 1)
    },
    // 点击tag
    handleClickTag (index, i, target) {
      this.activeArea = [index, target]
      const result = [index, i, target]
      this.activeTag = JSON.stringify(this.activeTag) === JSON.stringify(result) ? ['', '', ''] : result
    },
    // 清空按钮
    clearRule () {
      this.viewRuleList = [
        {
          conditions: [],
          consequence: []
        }
      ]
      this.ruleScript = this.ruleScriptTmp
      setTimeout(() => {
        this.editorCtrl.focus()
        this.editorCtrl.moveCursorTo(4, 12)
      }, 100)
    },
    // 编辑规则modal框取消按钮
    cancelEditRuleModal () {
      this.cancelNewRuleModal()
      this.editRuleShow = false
    },
    // 编辑规则modal确定按钮
    certainEditRuleModal () {
      // todo 根据不同tabs确定不同data，emit给父级组件
      // if (this.newRuleForm.ruleSetType === 'GDRL') {
      //   for (const item of this.viewRuleList) {

      //   }
      // }
      const gdrlContent = JSON.parse(JSON.stringify(this.viewRuleList))
      gdrlContent.forEach(item => {
        if (item.consequence && item.consequence.length) {
          let consequence = [[]]
          let index = 0
          item.consequence.forEach(ele => {
            if (ele.token === '&&') {
              index += 1
              consequence[index] = []
            } else {
              consequence[index].push(ele)
            }
          })
          item.consequence = consequence
        }
      })
      const params = {
        projectId: this.proId,
        resId: this.newRuleForm.resId
      }
      const data = {
        resId: this.newRuleForm.resId,
        resVerId: this.resVerId ? this.resVerId : undefined,
        content: this.newRuleForm.ruleSetType === 'DRL' ? this.ruleScript : gdrlContent,
        contentType: this.newRuleForm.ruleSetType === 'DRL' ? 'drl' : 'gdrl'
      }
      updateResourceContentByIdApi(params, data).then((res) => {
        const code = res.data.code
        const successText = '保存成功'
        const errorText = res.data.msg || '保存失败，请重试'
        showMessageTip(this, code, successText, errorText)
        if (code === 2000) {
          this.editRuleShow = false
          this.$emit('on-add-cancel')
          this.$emit('update-table')
        }
      })
    }
  },
  activated () {
  },
  mounted () {
  }
}
</script>

<style lang="less">
    /* 新增简单规则modal框 */
  .add-newrule-modal {
    .ivu-modal-body {
      padding: 0;
      .add-newrule-tab {
        .ivu-tabs-tabpane {
          padding: 0 16px 16px;
          min-height: 300px;
          max-height: 380px;
          overflow-y: auto;
        }
        &.edit-rule-tab {
          .ivu-tabs-bar {
            display: none;
          }
          .new-rule-tab {
            padding-top: 16px;
          }
        }
      }
    }
  }
  /* 新增复杂规则modal框 */
  .edit-rule-modal {
    .ivu-modal-body {
      background: #eee;
      max-height: 550px;
    }
    .edit-rule-content {
      display: flex;
      .left-content {
        flex: 1;
        margin-right: 4px;
        & > li {
          padding: 10px;
          border: 1px solid #fff;
          &:not(:last-child) {
            border-bottom: 0;
          }
        }
        .class-box {
          max-height: 130px;
          overflow-y: auto;
          border: 1px solid #fff;
          &.input-data-box {
            border-bottom: 0;
          }
          .data-item {
            width: 90px;
            margin: 5px 10px;
          }
          .data-title {
            font-weight: 400;
            padding-left: 10px;
          }
        }
      }
      .right-content {
        max-height: 530px;
        overflow-y: auto;
        flex: 1;
        border: 1px solid #fff;
        // 视图模式
        .view-model {
          padding: 20px;
          .view-box-title {
            font-size: 14px;
            text-align: center;
            margin-bottom: 10px;
            li {
              width: 44%;
              float: left;
              margin-right: 10px;
              border-bottom: 5px ridge #eee;
            }
            .add-btn > i {
              margin: 1px 0 0 1px;
            }
          }
          /* 输入规则、输出结果样式 */
          .view-box {
            .view-box-item {
              margin-bottom: 10px;
              & > p {
                width: 45%;
                height: 80px;
                float: left;
                background: #fff;
                overflow: hidden;
                &.active-area {
                  border: 1px solid #2d8cf0;
                  min-height: 80px;
                  height: auto;
                }
              }
              .left-area {
                margin-right: 6px;
              }
              .rm-btn {
                margin: 28px 0 0 10px;
              }
              /* tag自定义样式 */
              .view-tag {
                padding-right: 0;
                color: rgb(64, 158, 255);
                border: none;
                background: none;
                &:hover {
                  border-bottom: 1px solid #409eff;
                }
                &:hover > .ivu-icon-ios-close {
                  opacity: 1;
                  color: red;
                }
                .ivu-tag-text {
                  color: inherit;
                }
                .ivu-icon-ios-close {
                  opacity: 0;
                }
              }
              .active-tag {
                background-color: #2d8cf0;
                color: #fff;
              }
            }
          }
        }
        // 源码模式
        .code-model {
          width: 100%;
          height: 100%;
          .ace_print-margin {
            background: none;
          }
        }
        /* tag自定义样式 */
        .view-tag {
          color: rgb(64, 158, 255);
          border: none;
          background: none;
          &:hover {
            border-bottom: 1px solid #409eff;
          }
          &:hover > .ivu-icon-ios-close {
            opacity: 1;
            color: red;
          }
          .ivu-tag-text {
            color: inherit;
          }
          .ivu-icon-ios-close {
            opacity: 0;
          }
        }
      }
      .filter-wrap {
        display: flex;
        align-items: center;
      }
      .filter-board {
        padding-bottom: 4px;
        display: flex;
        align-items: center;
        & > b {
          min-width: 60px;
        }
      }
    }

    .edit-rule-footer {
      .left-btn {
        float: left;
      }
      .right-btn {
        float: right;
      }
    }
  }
</style>
